#Simple parser for extracting actions names from an gtk.UIManager's XML 
#descriptor
#usage:
#generate_actions <input xml> [output.xml]
#you can use "-" instead <input xml> for reading from stdin.
#if optional argument output.xml is not given, it will print to stdout
import os
import os.path
import sys
import xml.parsers.expat


try:
    input_f = sys.argv[1]
except Exception:
    print "usage: "
    print "        generate_actions <input.xml|-> [output.xml]"
    exit(1)

if input_f == "-":
    input = sys.stdin
else:
    input = open(input_f)

print len(sys.argv)
if len(sys.argv) == 2:
    output = sys.stdout
elif len(sys.argv) == 3:
    output_f = sys.argv[2]
    if os.path.exists(output_f):
        ans = raw_input(
            "Warning: %s already exists. Overwrite? [y/n]" % output_f)
        if ans.lower() != "y":
            print "Cancelled"
            exit(1)
    output = open(output_f, "w")
else:
    print "usage: "
    print "        generate_actions <input.xml|-> [output.xml]"
    exit(1)


actions_list = []

action_name = None
stock_id = None
label = None
accelerator = None
tooltip = None
callback = None

def start_element(name, attrs):
    try:
        action = attrs["action"]
    except KeyError:
        return
    actions_list.append(action)
    return

p = xml.parsers.expat.ParserCreate()
p.StartElementHandler = start_element
p.ParseFile(input)

actions_set = set(actions_list)
actions = list(actions_set)
actions.sort()
actions_list = [(
    name, 
    stock_id, 
    label, 
    accelerator, 
    tooltip, 
    callback) for name in actions]

print >>output, "actions_list = ["
for a in actions_list:
    print >>output, "   ", a, ","
print >>output, "    ]"
exit(0)
